package com.cheetah.start.module.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cheetah.start.common.annotation.Log;
import com.cheetah.start.common.base.result.Result;
import com.cheetah.start.common.base.result.ResultController;
import com.cheetah.start.common.base.result.ResultTable;
import com.cheetah.start.common.enums.BusinessTypeEnum;
import com.cheetah.start.common.enums.FileStatusEnum;
import com.cheetah.start.common.enums.LogTypeEnum;
import com.cheetah.start.common.query.PageQuery;
import com.cheetah.start.common.utils.MyHighLightUtil;
import com.cheetah.start.module.system.domain.SysFile;
import com.cheetah.start.module.system.service.SysFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.io.File;
import java.util.List;

/**
 * @author xjhmwj
 * @date 2021/8/7 14:39
 */
@Api(tags = "文件管理")
@Slf4j
@Validated
@RestController
@RequestMapping("/system/file")
public class SysFileController extends ResultController {
    @Autowired
    private SysFileService sysFileService;

    /**
     * 列表
     *
     * @param pageQuery 页面查询
     * @param cond      查询
     * @return {@link ResultTable}
     */
    @SaCheckPermission("sys:file:data")
    @ApiOperation(value = "文件列表")
    @GetMapping("/list")
    public ResultTable list(PageQuery pageQuery, String cond) {
        Page<SysFile> page = new Page<>(pageQuery.getPage(), pageQuery.getLimit());
        QueryWrapper<SysFile> wrapper = new QueryWrapper<>();
        boolean notBlank = StrUtil.isNotBlank(cond);
        if (notBlank) {
            wrapper.like("file_now_name", cond)
                    .or().like("file_name", cond);
        }
        wrapper.orderByDesc("create_time");
        sysFileService.page(page, wrapper);
        List<SysFile> records = page.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            for (SysFile record : records) {
                File file = new File(record.getFileRealPath());
                record.setExistStatus(file.exists() ? FileStatusEnum.EXIST.getCode() : FileStatusEnum.NOT_EXIST.getCode());
            }
            if (notBlank) {
                for (SysFile record : records) {
                    record.setFileNowName(MyHighLightUtil.highLight(record.getFileNowName(), cond));
                    record.setFileName(MyHighLightUtil.highLight(record.getFileName(), cond));
                }
            }
        }
        return pageTable(records, page.getTotal());
    }


    /**
     * 删除
     *
     * @param fileId 文件标识
     * @return {@link Result}
     */
    @SaCheckPermission("sys:file:delete")
    @ApiOperation(value = "删除文件")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/deleteOne")
    @Log(title = "文件", describe = "删除", type = BusinessTypeEnum.REMOVE, logType = LogTypeEnum.OPERATE)
    public Result delete(@NotNull(message = "ID不能为空") Integer fileId, String existStatus) {
        SysFile sysFile = sysFileService.getById(fileId);
        if (FileStatusEnum.EXIST.getCode().equals(existStatus)) {
            if (sysFile == null || FileStatusEnum.USE.getCode().equals(sysFile.getFileStatus())) {
                return failure("使用中不能删除");
            }
            File file = new File(sysFile.getFileRealPath());
            if (file.exists()) {
                boolean delete = file.delete();
                log.info("删除文件是否成功:[{}]", delete);
            }
        }
        return decide(sysFileService.removeById(fileId), BusinessTypeEnum.REMOVE);
    }


}
